package com.woniuxy.threeproject.end_water_project_user.controller;
import com.alipay.api.AlipayApiException;
import com.woniuxy.threeproject.end_water_project_user.commons.LateFeeCal;
import com.woniuxy.threeproject.end_water_project_user.commons.Result;
import com.woniuxy.threeproject.end_water_project_user.commons.UUIDUtils;
import com.woniuxy.threeproject.end_water_project_user.domain.*;
import com.woniuxy.threeproject.end_water_project_user.domain.form.BillByMonthReturn;
import com.woniuxy.threeproject.end_water_project_user.domain.form.billform.BillDetailForm;
import com.woniuxy.threeproject.end_water_project_user.domain.form.billform.GetBillForm;
import com.woniuxy.threeproject.end_water_project_user.domain.form.repairform.OderForm;
import com.woniuxy.threeproject.end_water_project_user.service.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * <p>
 * 缴费表 前端控制器
 * </p>
 *
 * @author Lucas
 * @since 2021-08-25
 */
@RestController
@Slf4j
@RequestMapping("/payment-form")
@CrossOrigin("*")
public class PaymentFormController {
    @Resource
    public IUserService iUserService;
    @Resource
    public IMeterreadingService iMeterreadingService;
    @Resource
    public IPaymentDetailService iPaymentDetailService;
    @Autowired
    private IPaymentFormService paymentFormService;

    @Resource
    public IPaymentFormService iPaymentFormService;

    @Resource
    private PayService payService;

    //查询缴费的方法
   ArrayList al= new ArrayList<Meterreading>();
    @GetMapping("getPayment")
    public Result getPayment(String card){
//        account.getAccount
        log.info("啦啦啦啦啦啦啦{}",card);
        User ru= iUserService.getUser(card);

       log.info("后台开始查询对应的用户为{}",ru);
        BillByMonthReturn u =new BillByMonthReturn();
//        设置用户id
        u.setUser_id(ru.getUserId());
        if(ru!=null){
        //card username address phone water_meter_id
            BeanUtils.copyProperties(ru,u);
        }else{
            log.info("=================");
            return Result.fail("4009","没有查询到该用户信息！");
        }
//        得到用水量、及其月份
        List<Meterreading> md=iMeterreadingService.getWaterNum(ru.getWaterMeterId());
        if(md.size()!=0){
            int waterNmu=0;
            for (int i = 0; i < md.size(); i++) {
                waterNmu+=md.get(i).getWaterNum();
            }
            //得到用户几个月欠的总用水量
            u.setWaterNum(waterNmu);
                //得到水的单价
            u.setPrice(md.get(0).getPrice());


            if(md.size()>1){
                //得到欠费的月数
//                u.setPay_month(md.get(0).getMeterReadingTime().getMonth()+1+"~"+(md.get(md.size()-1).getMeterReadingTime().getMonth()+1));
                u.setPay_month(md.size());
            }
//            else if(md.size()==1){
//                //如果只欠费一个月就显示一个月
//                u.setPay_month((md.get(0).getMeterReadingTime().getMonth()+1)+"");
//            }

            log.info("后台查询对应的水量:{}和月份数为：{}",waterNmu,md.size());
        }else{
//            表示没有欠费记录 正常状态
            return  Result.success();
        }



        double price = u.getPrice();
        int waterNum=u.getWaterNum();

//        double lateFee = u.getLateFee().doubleValue();
//        得到滞纳金
        Double  lateFee=getLateFee(card);
        u.setLateFee(lateFee);
        log.info("滞纳金：{}",lateFee);
        u.setTotal(price*waterNum+lateFee);
    // 一开始把未交费的水量表订单直接放在集合中
        al.add(u);
        return Result.success(u);
    }

//计算滞纳金


    public Double getLateFee(String card){
     //  表示费用
        Double fee=0.0;
        User ru= iUserService.getUser(card);
        List<Meterreading> waterNums = iMeterreadingService.getWaterNum(ru.getWaterMeterId());
//        if(waterNums.size()>0){
//            Date now = new Date();
//            Long day=1L;
////            表示延迟天数，
//            int lateDay=0;
//            for (int i = 0; i < waterNums.size(); i++) {
//
//                day= (new Date().getTime()- waterNums.get(i).getLastMeterTime().getTime())/(1000*60*60*24)-40;
//                log.info("上次抄表日间隔时间为：{}",day);
////                到结算日起算 超过出账单日10天（30+10）天每天计收1毛
//                if(day>0){
//                    lateDay+=day;
//                }
//            }
//            fee=lateDay*0.1;
////            log.info("延迟天数:{}",lateDay);
//        }else{
//             fee=0.0;
//        }
//
//        return fee;
         fee = LateFeeCal.lateFee(waterNums);
        return fee;
    }

    /*
    查询发票详情
     */
    @GetMapping("getBillDetail")
    public Result getBillDetail(String card,String billNum){
        log.info("开始执行查询发票业务,{}{}",card,billNum);
        GetBillForm getBillForm = new GetBillForm();
        getBillForm.setCard(card);
        getBillForm.setBillNum(billNum);
        BillDetailForm billDetailForm = paymentFormService.getBillDetailForm(getBillForm);
        log.info("============================================");
        return Result.success(billDetailForm);
    }
//如果缴费成功，前台返回一个标志位修改其状态并计算每个月的费用情况
//    @GetMapping("getDetail")
//    public void getDetail(Boolean flag,String card){
////    flag如果为true    表示缴费成功了
//        if(flag){
//            log.info("缴费已经成功！开始更新后台水量表的状态！");
////            修改其用水表的状态为1（已经缴费）,根据卡号查询用户信息
//            User user = iUserService.getUser(card);
////            用户信息查询水表
//            int i = iMeterreadingService.updateStaet(user.getWaterMeterId());
//            if(i>0){
//            //表示修改状态成功
//                log.info("卡号为{}修改状态成功！",card);
//           // 修改状态成功后，就生成费用表，工具类自动生成发票号
//                log.info("开始自动生成费用表！");
//                String fpuUid = UUIDUtils.getFPUUid();
//               //  记录月数
////                Result pay = getPayment(card);
//                log.info("{}",al);
//                BillByMonthReturn bmr=(BillByMonthReturn) al.get(0);
//                double bill_money=bmr.getTotal();
//                log.info("缴费总金额:{}",bill_money);
//                //记录月数
//                 log.info("{}",bmr.getPay_month());
//                String month= bmr.getPay_month();
//
//                String start = month.substring(0, 1);
//                String end = month.substring(month.length() - 1);
//                log.info("{},{}",start,end);
//                Integer sm = Integer.valueOf(start);
//                Integer em = Integer.valueOf(end);
//                Integer cjMon=em-sm;
//                log.info("参数为的长度为：{}",em-sm);
//
//                //记录支付方式(默认支付宝)
//                String payway="c";
//                PaymentForm p = new PaymentForm();
//                p.setBillMoney(bill_money);
//                p.setBillNum(fpuUid);
//                p.setEmployeeId(1);
//                p.setPayMonth(cjMon);
//                p.setPayWay(payway);
//                p.setUserId(bmr.getUser_id());
//                //生成费用表
//               int z= iPaymentFormService.insert(p);
//                if(z>0){
//                    //加入成功得到费用表自动生成的ID号（更加发票号）
//                    log.info("成功生成费用表，开始获取费用表id");
//                PaymentForm pf=iPaymentFormService.getPayFormId(fpuUid);
//                    //如果返回的值不为空，就修改费用明细表明细；
//                    if(pf!=null){
//                        Integer payId = pf.getPaymentFormId();
//                    //生成费用明细表
//                        log.info("开始生成费用明细表！");
//                        CreatePayDail(payId,card);
//                    }
//
//                }
//            }else{
////                表示修改失败
//                log.info("卡号为{}修改状态失败！",card);
////                return  Result.fail("4004","系统开小差了！");
//            }
//
//
//        }
//    }
//    把生成的数据写入到费用详细表中去
    private void CreatePayDail(Integer payId,String card) {
        PaymentDetail p = new PaymentDetail();
        p.setEmployeeId("1");
        p.setPaymentFormId(payId);
//        Result pay = getPayment(card);
//        BillByMonthReturn bmr=(BillByMonthReturn) pay.getObject();
        BillByMonthReturn bmr=(BillByMonthReturn) al.get(0);
        p.setWaterNum(Double.valueOf(bmr.getWaterNum()));
        p.setPrice(bmr.getPrice());
        p.setReceivable(bmr.getTotal());
        p.setLateFee(bmr.getLateFee());
        User user = iUserService.getUser(card);
        p.setUserId(user.getUserId());
        //加入数据库中
        int i=iPaymentDetailService.add(p);
        if(i>0){
            log.info("生成费用明细表成功！");
        }
    }
    //添加缴费及详情
    @PostMapping("addOrder")
    private String addPaymentForm(@RequestBody OderForm oderForm) throws AlipayApiException {
        log.info("缴费功能：接收用户信息：{}",oderForm);
        PaymentForm paymentForm = new PaymentForm();
        Integer paymentFormID = paymentFormService.findEndPaymentForm();
        paymentForm.setBillMoney(oderForm.getBillMoney());
        paymentForm.setPayMonth(oderForm.getPayMonth());
        paymentForm.setBillNum("wn2021"+(paymentFormID+1));
        paymentFormService.addPayForm(paymentForm,oderForm.getCard());
        String outTradeNo = paymentForm.getBillNum();
        String subject="水费缴费";
        String totalAmount = paymentForm.getBillMoney()+"";
        log.info("支付功能：接收用户请求，{} {} {}",outTradeNo,subject,totalAmount);
        AlipayBean alipayBean = AlipayBean.getAlipayBean();
        alipayBean.setOut_trade_no(outTradeNo);
        alipayBean.setSubject(subject);
        alipayBean.setTotal_amount(totalAmount);
        alipayBean.setBody(null);
        return payService.aliPay(alipayBean);
    }
    @PostMapping("ok")
    public void updateState(){
        log.info("缴费成功,修改订单状态和支付方式");
        AlipayBean alipayBean = AlipayBean.getAlipayBean();
        paymentFormService.updatePaymentForm(alipayBean.getOut_trade_no(),'c');
    }

}

